package com.hjb.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ChatClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                      .channel(NioSocketChannel.class)
                      .handler(new ChannelInitializer<SocketChannel>() {
                          @Override
                          protected void initChannel(SocketChannel socketChannel){
                              //socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(10000, Delimiters.lineDelimiter()));
                              //编码
                              socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                              //解码
                              socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                              //自定义处理
                              socketChannel.pipeline().addLast(new MyChatClientHandler());
                          }
                      });

                Channel channel = bootstrap.connect("localhost",8099).sync().channel();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
                while(true){
                    channel.writeAndFlush(bufferedReader.readLine()+"\r\n");
                }

        }finally {
            eventLoopGroup.shutdownGracefully();
        }

    }
}
